package com.heima.wemedia.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {
        //1.校验参数
        if (file == null || file.getSize() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 上传图片到MinIO中
        //2.1 使用UUID生成文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");

        //2.2 拿到文件的后缀
        String originalFilename = file.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));

        //2.3 上传文件
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + fileType, file.getInputStream());
            log.info("上传图片到minIO成功，fileId:{}",fileId);        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl上传图片失败");
        }

        //3. 保存图片信息到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0); //0 图片 1 视频
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4. 返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //校验参数
        dto.checkParam();
        //构建分页对象
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());

        // 查询
        Page<WmMaterial> wmMaterialPage = this.lambdaQuery()
                .eq(dto.getIsCollection() != null && dto.getIsCollection() == 1, WmMaterial::getIsCollection, dto.getIsCollection())
                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
                .orderByDesc(WmMaterial::getCreatedTime)
                .page(page);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return pageResponseResult;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ResponseResult del(Integer id) throws Exception {
        //先查看是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count == 0){
            boolean result = this.removeById(id);
            if (!result){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        }
        return ResponseResult.okResult(200,"操作成功");
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        //修改收藏状态
        boolean result = this.lambdaUpdate()
                .eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 0)
                .update();
        if (!result){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(200,"操作成功");
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //修改收藏状态
        boolean result = this.lambdaUpdate()
                .eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 1)
                .update();
        if (!result){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(200,"操作成功");
    }
}
